#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import re
import pathlib


class LadderDiagram:

    def __init__(self, filepath):
        self._itemDict = dict()

        lineList = pathlib.Path(filepath).read_text().split("\n")
        lastScore = 999999999.0
        cols = dict()
        for i in range(0, lineList):
            # get all elements in this line
            elist = [_Element(i, m) for m in re.finditer(r'(\S+) (.*) \[([0-9.]*)\]', lineList[i])]
            if len(elist) == 0:
                continue

            # check element position
            for e in elist:
                if e.start in cols:
                    cols[e.start] = max(e.end, cols[e.start])
                else:
                    cols[e.start] = e.end
                for start, end in cols.items():
                    if e.start == start and e.end <= end:
                        continue
                    if e.end < start or e.start > end:
                        continue
                    raise LadderDiagramError('element "%s %s" has invalid position' % (e.vendor, e.model))

            # detect if there's one element with score
            scoreElem = None
            for e in elist:
                if e.score is None:
                    continue
                if e.score >= lastScore:
                    raise LadderDiagramError('score of element "%s %s" is too large' % (e.vendor, e.model))
                scoreElem = e
                break

            if scoreElem is not None:
                # all elements should take scoreElem's score
                for e in elist:
                    if e.score is not None:
                        raise LadderDiagramError('element "%s %s" and "%s %s" should have same score' % (scoreElem.vendor, scoreElem.model, e.vendor, e.model))
                    else:
                        e.score = scoreElem.score
            else:
                # all elements should take a calculated score
                for e in elist:
                    e.score = lastScore - 1

            # put all elemtns in self._itemDict
            for e in elist:
                if e.vendor not in self._itemDict:
                    self._itemDict[e.vendor] = dict()
                if e.model in self._itemDict[e.vendor]:
                    raise LadderDiagramError('duplicate element "%s %s" found' % (e.vendor, e.model))
                self._itemDict[e.vendor][e.model] = e

            # update lastScore
            lastScore = elist[0].score

    def exists(self, vendor, model):
        return (vendor in self._itemDict and model in self._itemDict[vendor])

    def get_score(self, vendor, model):
        return self._itemDict[vendor][model]


class LadderDiagramError(Exception):
    pass


class _Element:

    def __init__(self, lineNo, m):
        self.line = lineNo
        self.start = m.start()
        self.end = m.end()
        self.vendor = m.group(0)
        self.model = m.group(1)
        self.score = float(m.group(2)) if m.group(2) != "" else None
